const app = getApp();

Page({
    data: {
        faultType: '',
        faultArea: '',
        faultDescribe: '',
        areaDescribe: '',
        faultPhoto: ''
    },
    inputFaultType: function (e) {
        this.setData({
            faultType: e.detail.value
        });
    },
    inputFaultArea: function (e) {
        this.setData({
            faultArea: e.detail.value
        });
    },
    inputFaultDescribe: function (e) {
        this.setData({
            faultDescribe: e.detail.value
        });
    },
    inputAreaDescribe: function (e) {
        this.setData({
            areaDescribe: e.detail.value
        });
    },
    chooseFaultPhoto: function () {
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            success: (res) => {
                if (res.tempFiles.length > 0) {
                    this.setData({
                        faultPhoto: res.tempFiles[0].tempFilePath
                    });
                }
            }
        });
    },
    submitRepair: async function () {
        const token = app.globalData.token;
        if (!token) {
            wx.showToast({
                title: '未获取到有效token，请先登录',
                icon: 'none'
            });
            return;
        }
        let url = 'http://8.140.225.174:5000/faultlist_add';
        let formData = {
            CusId: app.globalData.openId,
            Faulttype: this.data.faultType,
            FaultArea: this.data.faultArea,
            FaultDescribe: this.data.faultDescribe,
            AreaDescribe: this.data.areaDescribe
        };
        let header = {
            'token': app.globalData.token
        };

        if (this.data.faultPhoto) {
            const fileData = await this.getFileData(this.data.faultPhoto);
            if (fileData) {
                formData = {
                    ...formData,
                    FaultPhoto: fileData
                };
            } else {
                wx.showToast({
                    title: '图片文件处理失败，无法提交报修单',
                    icon: 'none'
                });
                return;
            }
        }

        try {
            const resData = await this.sendSubmitRepairRequest(url, formData, header);
            if (resData && resData.code === 200) {
                wx.showToast({
                    title: '报修单添加成功',
                    icon: 'success'
                });
                wx.navigateBack({
                    delta: 1
                });
            } else if (resData && resData.code === 500) {
                wx.showToast({
                    title: '报修单添加失败',
                    icon: 'none'
                });
            } else {
                wx.showToast({
                    title: '报修单提交出现未知错误',
                    icon: 'none'
                });
            }
        } catch (error) {
            wx.showToast({
                title: '网络错误，无法提交报修单',
                icon: 'none'
            });
        }
    },
    getFileData: function (filePath) {
        return new Promise((resolve, reject) => {
            wx.getFileSystemManager().readFile({
                filePath: filePath,
                encoding: 'base64',
                success: (res) => {
                    const fileBase64 = `data:image/jpeg;base64,${res.data}`;
                    resolve(fileBase64);
                },
                fail: (err) => {
                    console.error('读取文件失败，详细信息：', err);
                    reject(err);
                }
            });
        });
    },
    sendSubmitRepairRequest: function (url, formData, header) {
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: url,
                filePath: this.data.faultPhoto,
                name: 'FaultPhoto',
                formData: formData,
                header: header,
                success: (res) => {
                    const parsedData = JSON.parse(res.data);
                    resolve(parsedData);
                },
                fail: (err) => {
                    reject(err);
                }
            });
        });
    }
});